package drds.data_propagate.binlog_event_filter.aviater;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import drds.common.$;
import drds.data_propagate.binlog_event_filter.BinlogEventFilter;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 基于aviater进行tableName简单过滤计算，不支持正则匹配
 */
public class AviaterSimpleBinlogEventFilter implements BinlogEventFilter<String> {


    //
    private static final String FILTER_EXPRESSION = "include(list,target)";
    //
    private static final String SPLIT = ",";
    private final Expression expression = AviatorEvaluator.compile(FILTER_EXPRESSION, true);
    private final List<String> list;

    public AviaterSimpleBinlogEventFilter(String filterExpression) {
        if (StringUtils.isEmpty(filterExpression)) {
            list = new ArrayList<String>();//all
        } else {
            String[] splits = filterExpression.toLowerCase().split(SPLIT);
            list = Arrays.asList(splits);
        }
    }

    /**
     * @param target 在校验的时候满足入参是list其中的一个元素即可,如果list为{}都返回为true.如果传入参数为空则返回异常 eg:list='x,y' , 入参是'x,y'返回是false.因为list是使用,分割
     */
    public boolean filter(String target) {
        if (!$.isHasData(list)) {//all
            return true;
        }
        if ($.isNullOrEmpty(target)) {
            throw new IllegalArgumentException("target必须含有业务意义");
        }
        Map<String, Object> env = new HashMap<String, Object>();
        env.put("list", list);
        env.put("target", target.toLowerCase());
        return (Boolean) expression.execute(env);
    }

}
